<?php
/* 
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
 date_default_timezone_set('Asia/Ho_Chi_Minh');
class Connection{
    private $conn = NULL;
    private $host = "localhost";
	/**
	 * localhost
	 * */
	public $BASE_URL = "http://localhost/vnaloha-shop/"; 
    private $username = "root";
    private $password = "";
    private $database = "vnaloha_shop";
	
    private $charset = "UTF-8";
    /**
     * Contruct class Connection
     */
    function  __construct() {
        $this->conn = mysql_connect($this->host, $this->username, $this->password);
        mysql_select_db($this->database);
        mysql_query("set names 'utf8'");
    }

    /** Hiển thị tất cả các field in 1 table
     * @param $table
     * @return array
     */
    public function show_field_table($table){
        $query = " SHOW FIELDS FROM ".$table;
        $result = mysql_query($query) or die(mysql_error());
        $array = array();
        while($row = mysql_fetch_array($result)){
            $array[] = $row;
        }
        return $array;
    }

    /**
     * @param null $table
     * @param null $attributes
     * @return int
     */
    public function insert($table=NULL,$attributes=NULL){
		if($table == NULL || $attributes == NULL){
    		return 0;
    	}else{
    		$field = "";
			$val = "";
    		$str = "INSERT INTO ".$table." ";
			try{
				foreach ($attributes as $key => $value) {
					$field = $field . $key . ",";
					$val = $val . $value . ",";
				}
				
				$field = substr($field, 0, strlen($field) - 1);
				$val = substr($val, 0, strlen($val) - 1);				
				$str = $str .'('.$field.') VALUES('.$val.')';
				// echo $str; die;
				$res = mysql_query($str) or die(mysql_error());
				if($res)
					return mysql_insert_id();
				else return 0;
			}catch(exception $e){
				return 0;
			}
    	}
	}

    /**
     * @param null $table
     * @param null $attributes
     * @return bool
     */
    public function update($table=NULL, $attributes=NULL){
    	if($table == NULL || $attributes == NULL){
    		return false;
    	}else{
    		$query = "UPDATE " . $table . " SET ";
    		try{
    			$id_record = 0;
	            foreach ($attributes as $key => $value) {
	                if ($key != "id")
	                    $query = $query . $key . "='" . $value . "',";
	                else
	                    $id_record = $value;
	            }
	            $query = substr($query, 0, strlen($query) - 1);
	            $query = $query . " WHERE id='$id_record'";		
				// echo $query; die;		
	            mysql_query($query) or die(mysql_error());
				return true;
    		}catch(exception $e){
    			return false;
    		}
    	}
    }

    /**
     * @param $query
     * @return array
     */
    public function get_one_data($query){
        $result = mysql_query($query) or die(mysql_error());
        return mysql_fetch_array($result);
    }

    /**
     * @param $query
     * @return array
     */
    public function get_list_data($query){
        $result = mysql_query($query) or die(mysql_error());
        $array = array();
        while($row = mysql_fetch_array($result)){
            $array[] = $row;
        }
        return $array;
    }

    /**
     * @param $table
     * @param $id
     * @param $status
     * @param string $option1
     * @param string $option2
     * @return array
     */
    public function get_all_data($table, $id = -1, $status = -1, $option1 = '', $option2 = ''){
        settype($id, 'int');        settype($status, 'int');
        $query = "SELECT * FROM ".$table." WHERE
                    (status ='$status' or '$status' = -1)
                    AND (id = '$id' or '$id' = -1)" . $option1 . "
                    ORDER BY id DESC " . $option2;
        // echo $query; 	
        if($id == -1)
            return $this->get_list_data ($query);
        else
            return $this->get_one_data ($query);
    }
	 public function get_all_data_fix($table, $id = -1, $status = -1, $option1 = '', $option2 = ''){
        settype($id, 'int');        settype($status, 'int');
        $query = "SELECT * FROM ".$table." WHERE
                    (status ='$status' or '$status' = -1)
                    AND (id = '$id' or '$id' = -1)" . $option1 . " " . $option2;
        // echo $query; die();
        if($id == -1)
            return $this->get_list_data ($query);
        else
            return $this->get_one_data ($query);
    }
    public function get_maxrow_of_table($table, $option1 = ''){
        $maxResult = 0;
        $query = "SELECT count(*) as max FROM ".$table." WHERE 1 ". $option1;
		// echo $query;
        $result = mysql_query($query) or die(mysql_error());
        while($row = mysql_fetch_array($result)){
            $maxResult = $row['max'];
        }
        return $maxResult;
    }
	function delete_list_data_db($table,$listid) {
    	$idlist = explode(",",$listid); 
		for ($i=0 ; $i<count($idlist) ; $i++){
			$id=$idlist[$i]; 
			$this->delete_one_record($table,$id);
		}	
    }

    /**
     * @param $table
     * @param $id
     * @return bool
     */
    public function delete_one_record($table, $id){
        settype($id, 'int');
        $detail = $this->get_all_data($table, $id);
		
		if($detail != null && !empty ($detail)){
			
			if($detail['url_image'] != null){
				$fileDelete = "../../uploads/gallery/".$detail['url_image'];
				if(file_exists($fileDelete)){
					unlink($fileDelete);
				}
			}
            $query = "DELETE FROM " . $table . " WHERE id=".$id;
            mysql_query($query) or die(mysql_error());
            return mysql_affected_rows() == 1 ; 
        }
		return false;
    }

    /**
     * @param $table
     * @param $list_id
     * @return bool
     */
    public function delete_many_record($table, $list_id){
        $query = "DELETE FROM " . $table . " WHERE id IN (";
        $temp = count($list_id)-1;
        for ($i = 0; $i <= $temp; $i++) {            
            if($i == $temp)
                $query = $query . $list_id[$i];
            else
                $query = $query . $list_id[$i] . ",";        
        }        
        $query = $query . ")";            
        mysql_query($query) or die(mysql_error());
        return mysql_affected_rows() == count($list_id);
    }

    /**
     * @param $totalRows
     * @param int $pageNum
     * @param int $pageSize
     * @param int $offset
     * @return string
     */
    function pageList($totalRows, $pageNum=1, $pageSize = 5, $offset = 5) {
        $baseURL = $_SERVER['PHP_SELF'];
        parse_str($_SERVER['QUERY_STRING'], $arr);       
        unset($arr['pageNum']);
        foreach ($arr as $k => $v)
            $str.= "&{$k}={$v}";
        $baseURL .="?" . $str;        

        if ($totalRows <= 0)
            return "";
        $totalPages = ceil($totalRows / $pageSize);
        if ($totalPages <= 1)
            return "";

        $firstLink = "<li><a href='$baseURL' title='First Page'>«</a></li>";
        $prevLink = "";
        $nextLink = "";
        $lastLink = "<li><a href='$baseURL&pageNum=$totalPages' title='Last Page'>»</a></li>";

        if ($pageNum > 1) {
            $prevPage = $pageNum - 1;
            $prevLink = "<li><a href='$baseURL&pageNum=$prevPage' title='Previous Page'>&laquo;</a></li>";
        }
        if ($pageNum < $totalPages) {
            $nextPage = $pageNum + 1;
            $nextLink = "<li><a href='$baseURL&pageNum=$nextPage' title='Next Page'>&raquo;</a></li>";
        }

        $from = $pageNum - ceil($offset/2);
        $to = $pageNum + ceil($offset/2);       
        if ($from <= 0) {
            $from = 1;
            $to = $offset;
        }
        if ($to > $totalPages) {
            $to = $totalPages;
        }
        $links = "";        
        for ($j = $from; $j <= $to; $j++) {
            if ($j == $pageNum)
                $links = $links . "<li class='active'><a href='javascript:void(0);' class='number' title='$j'>$j</a></li>";
            else
                $links = $links . "<li><a href='$baseURL&pageNum=$j' class='number' title='$j'>$j</a></li>";
        } //for
        return $firstLink . $prevLink . $links . $nextLink . $lastLink;
    }

    /**
     * @param $username
     * @return array
     */
    public function check_user_username($username){
		$query = "SELECT COUNT(*) FROM user WHERE username='$username'";
		return $this->get_one_data($query);
	}

    /**
     * @param $email
     * @return array
     */
    public function check_user_by_email($email){
		$query = "SELECT COUNT(*) FROM user WHERE email='$email'";
		return $this->get_one_data($query);
	}
}
?>